<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form small-top">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
             id="form"
          >
            <el-form-item label="商品分类：" prop="category_id" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
                @change="getArticleList"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="记录时间：" prop="time" class="wid220">
              <el-date-picker
                v-model="time"
                type="daterange"
                range-separator="至"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="datePick"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="商品名称：" prop="goods_spu_id">
              <change-goods-input
                isInventory
                ref="changeGoodsInput"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button @click="exportConfirm">导出</el-button>
            </MainFormBtn>
          </el-form>
        </div>
        <!-- 表单数据 -->
        <div class="main_table">
          <el-table
            ref="multipleTable"
            class="mg-t-4"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
            :header-cell-class-name="this.$verticaline"
            :height="borderHeight"
            :header-cell-style="tableHeightStyle"
            @header-dragend="changeTableWidth"
          >
            <!-- <el-table-column type="selection"></el-table-column> -->
            <el-table-column
              label="序号"
              fixed
              prop="userId"
              :width="tableWidth[hash + 'userId'] || 80"
            >
              <template slot-scope="scope">{{
                (current.page - 1) * current.per_page + scope.$index + 1
              }}</template>
            </el-table-column>
            <el-table-column
              label="商品名称"
              prop="spu_name"
              :width="tableWidth[hash + 'spu_name']"
            >
              <template slot-scope="scope">
                {{ scope.row.name + "【" + scope.row.spu_name + "】" }}
              </template>
            </el-table-column>
            <el-table-column
              label="单位"
              prop="unit"
              :width="tableWidth[hash + 'unit']"
            ></el-table-column>
            <el-table-column
              label="期初数量"
              prop="opening_stock"
              :width="tableWidth[hash + 'opening_stock']"
            ></el-table-column>
            <el-table-column
              label="入库数量"
              prop="storage_num"
              :width="tableWidth[hash + 'storage_num']"
            ></el-table-column>
            <el-table-column
              label="出库数量"
              prop="stock_out_num"
              :width="tableWidth[hash + 'stock_out_num']"
            ></el-table-column>
            <el-table-column
              label="期末数量"
              prop="closing_stock"
              :width="tableWidth[hash + 'closing_stock']"
            ></el-table-column>

            <el-table-column
              label="期初金额"
              prop="opening_money"
              :width="tableWidth[hash + 'opening_money']"
            ></el-table-column>

            <el-table-column
              label="入库金额"
              prop="storage_money"
              :width="tableWidth[hash + 'storage_money']"
            ></el-table-column>

            <el-table-column
              label="出库金额"
              prop="stock_out_money"
              :width="tableWidth[hash + 'stock_out_money']"
            ></el-table-column>

            <el-table-column
              label="期末金额"
              prop="closing_money"
              :width="tableWidth[hash + 'closing_money']"
            ></el-table-column>

            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              prop="operate"
              :width="tableWidth[hash + 'operate'] || 240"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <router-link
                  :to="{
                    name: 'warehouse_records_detail',
                    query: {
                      start_time: form.start_time,
                      end_time: form.end_time,
                      id: scope.row.goods_spu_id,
                    },
                  }"
                >
                  <el-link>明细</el-link>
                </router-link>
                <el-link
                  style="color: rgb(17, 138, 178)"
                  @click="exportOrderiInfo(scope.row.goods_spu_id)"
                  >导出</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  stockLog_list,
  stockLog_index,
  export_stocklog_list,
  export_stocklog_detail,
} from "@/api/warehouse/warehouseLog";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime, exportMethod } from "@/utils/index";
import { recursion, category } from "@/utils/index";
export default {
  mixins: [mixins],
  components: {},
  data() {
    return {
      parseTime,
      exportMethod,
      // 加载中
      list: null,
      listLoading: true,
      // 分页样式
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,

      // 列表数据
      list: [],
      listLoading: false,
      // 搜索
      form: {
        goods_spu_id: "",
        pid: "",
        category_id: [],
        start_time: parseTime(new Date(), "{y}-{m}-{d}"),
        end_time: parseTime(new Date(), "{y}-{m}-{d}"),
      },
      // 记录时价范围选择
      time: [
        parseTime(new Date(), "{y}-{m}-{d}"),
        parseTime(new Date(), "{y}-{m}-{d}"),
      ],
      // 更多
      moredata: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      // 选择全部
      selectArr: [],
      moredata: false,
    };
  },
  activated() {
    this.getNumerical(200);
    this.stockLogIndex();
  },
  created() {},
  methods: {
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 搜索
    getArticleList() {
      this.stockLogIndex();
    },
    startGetting() {
      this.getArticleList();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.$refs["changeGoodsInput"].name = "";
      this.form.start_time = this.parseTime(new Date(), "{y}-{m}-{d}");
      this.form.end_time = this.parseTime(new Date(), "{y}-{m}-{d}");
      this.time = [
        parseTime(new Date(), "{y}-{m}-{d}"),
        parseTime(new Date(), "{y}-{m}-{d}"),
      ];
      this.stockLogIndex();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.stockLogIndex();
    },
    changePage(page) {
      this.current.page = page;
      this.stockLogIndex();
    },
    // 日期选择
    datePick() {
      if (this.time) {
        this.form.start_time = this.time[0];
        this.form.end_time = this.time[1];
        this.getArticleList();
      }
    },
    exportOrderiInfo(id) {
      let form = this.list_form();
      let params = {
        start_time: form.start_time,
        end_time: form.end_time,
        goods_spu_id: id,
        type: "",
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, params)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        params
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_stocklog_detail(data)
        .then((res) => {
          this.exportMethod(res, "库存明细", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },

    // 表头导出
    exportConfirm() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_stocklog_list(data)
        .then((res) => {
          this.exportMethod(res, "库存记录", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
    // 请求库存列表
    stockLogIndex() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      stockLog_index(data).then((res) => {
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          this.list = res.data;
          this.totalCount = res.data.total;

          let arr = [];
          for (let i in res.data.list) {
            arr.push(res.data.list[i]);
          }
          this.list = arr;
          this.form.start_time = res.data.start_time;
          this.form.end_time = res.data.end_time;
        }
        this.listLoading = false;
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 监听表单全选事件
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}
</style>
